const express = require("express");
const assert = require("http-assert");

const router = express.Router({
  mergeParams: true,
});

router.get("/", async (req, res) => {
  let { page = 1, limit = 10, skip, sort, populate, where = {} } =
    req.query || {};

  page = Number(page);
  limit = Number(limit);
  skip = skip || (page - 1) * limit;
  if (Object.keys(where).length != 0) {
    where = JSON.parse(where);
  }
  const data = await req.Model.find()
    .where(where)
    .skip(skip)
    .limit(limit)
    .sort(sort)
    .populate(populate);

  const total = await req.Model.countDocuments(where);
  res.send({
    data,
    total,
    lastPage: Math.ceil(total / limit),
    currentPage: page,
  });
});

router.get("/:id", async (req, res) => {
  const model = await req.Model.findById(req.params.id);
  res.send(model);
});

router.post("/", async (req, res) => {
  console.log(req.user);
  assert(req.user.purview === 1, 403, "对不起,您暂时没有修改系统内容的权限");
  const model = await req.Model.create(req.body);
  res.send(model);
});

router.put("/:id", async (req, res) => {
  assert(req.user.purview === 1, 403, "对不起,您暂时没有修改系统内容的权限");
  const model = await req.Model.findByIdAndUpdate(req.params.id, req.body);
  res.send(model);
});

router.delete("/:id", async (req, res) => {
  assert(req.user.purview === 1, 403, "对不起,您暂时没有修改系统内容的权限");
  await req.Model.findByIdAndRemove(req.params.id, req.body);
  res.send({
    success: true,
  });
});

module.exports = router;
